package com.blog.service.impl;

import com.blog.entity.article.Article;
import com.blog.entity.comment.Comment;
import com.blog.mapper.ArticleMapper;
import com.blog.mapper.CommentMapper;
import com.blog.service.ArticleService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Resource
    private ArticleMapper mapper;
    @Resource
    private CommentMapper commentMapper;

    @Override
    public List<Article> getArticlesByAudit(String audit) {
        return mapper.getArticlesByAudit(audit);
    }

    @Override
    public List<Article> getArticleByTid(Integer tid) {
        return mapper.getArticleByTid(tid);
    }

    @Override
    public List<Article> getArticleByUid(Integer uid) {
        return mapper.getArticleByUid(uid);
    }

    @Override
    public Article getArticleByAid(Integer aid) {
        return mapper.getArticleByAid(aid);
    }

    @Override
    public String addArticle(Article article) {
        return mapper.addArticle(article) > 0 ? null : "发布文章失败,请稍后再试";
    }

    @Override
    public String updateArticle(Article article) {
        article.setAudit("0");
        article.setViews(0);
        return mapper.updateArticle(article) > 0 ? null : "修改文章失败,请稍后再试";
    }

    @Override
    public Integer updateArticleAudit(Article article) {
        Article newArticle = mapper.getArticleByAid(article.getAid());
        newArticle.setAudit(article.getAudit());
        newArticle.setViews(0);
        return mapper.updateArticle(newArticle) > 0 ?
                newArticle.getAudit().equals("1") ? 1 : newArticle.getAudit().equals("2") ? 2 : 0 : 0;
    }

    @Override
    public String updateArticleView(Article article) {
        Article newArticle = mapper.getArticleByAid(article.getAid());
        if (newArticle.getViews() == null) {
            newArticle.setViews(1);
        } else {
            newArticle.setViews(newArticle.getViews() + 1);
        }
        return mapper.updateArticle(newArticle) > 0 ? null : "浏览量加载出错,请稍后再试";
    }

    @Override
    public String deleteArticle(Integer aid) {
        List<Comment> comments = commentMapper.getCommentsByAid(aid);
        for (Comment comment : comments) {
            if (!(commentMapper.deleteComment(comment.getCid()) > 0))
                return "删除文章评论失败,请稍后再试";
        }

        return mapper.deleteArticleByAid(aid) > 0 ? null : "删除文章失败,请稍后再试";
    }
}
